import mqtt from '../../utils/mqtt.js';
const aliyunOpt = require('../../utils/aliyun/aliyun_connect.js')
const onfire=require('../../utils/onfire1.0.6.js')
const app = getApp();
const db = wx.cloud.database();
Page({
  ColorList: app.globalData.ColorList,
  color:'red',//进度条相关
  options: {
    addGlobalClass: true,
  },
  lock_open:'{"id": 123,"version": 1.0,"method": "thing.event.property.post","params": {"PowerSwitch": 1}}',
  lock_close:'{"id": 123,"version": 1.0,"method": "thing.event.property.post","params": {"PowerSwitch": 0}}',
  data: {
    PageCur: 'basics',
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    client: null,
    //记录重连的次数
    reconnectCounts: 0,
    //MQTT连接的配置
    options: {
      protocolVersion: 4, //MQTT连接协议版本
      clean: true,
      keepalive:60,
      reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
      connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
      resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
      clientId: '',
      password: '',
      username: '',
    },
    topic: {
      LEDcontrolTopic: '/sys/a1VO16ZKJTN/wechat-app/thing/event/property/post',
      HumdTopic: '/sys/a1VO16ZKJTN/wechat-app/thing/service/property/set',
    },
    aliyunInfo: {
      productKey: 'a1VO16ZKJTN', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
      deviceName: 'wechat-app', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
      deviceSecret: '0feaa211d2f9f0454eb066a834bf3dc3', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
      regionId: 'cn-shanghai', //阿里云连接的三元组 ，请自己替代为自己的产品信息!!
    },
    LEDValue: [{
      LEDlogo: '../../images/lock-close.png',
      ButtonValue: '关灯',
      ButtonFlag: false,
    }],
    avatarUrl: '',
    userInfo: {},
  },
      NavChange(e) {
        this.setData({
          PageCur: e.currentTarget.dataset.cur
        })
      },
      onLoad: function(options) {
        var that = this
        //传进去三元组等信息，拿到mqtt连接的各个参数
        let clientOpt = aliyunOpt.getAliyunIotMqttClient({
          productKey: that.data.aliyunInfo.productKey,
          deviceName: that.data.aliyunInfo.deviceName,
          deviceSecret: that.data.aliyunInfo.deviceSecret,
          regionId: that.data.aliyunInfo.regionId,
          port: that.data.aliyunInfo.port,
        });
        //console.log("get data:" + JSON.stringify(clientOpt));
        //得到连接域名
        let host = 'wxs://' + clientOpt.host;
        this.setData({
          'options.clientId': clientOpt.clientId,
          'options.password': clientOpt.password,
          'options.username': clientOpt.username,
        })
        console.log("this.data.options host:" + host);
        console.log("this.data.options data:" + JSON.stringify(this.data.options));
        //开始连接
        this.data.client = mqtt.connect(host, this.data.options);
        this.data.client.on('connect', function(connack) {
          wx.showToast({
            title: '连接成功'
          })
        })
        that.data.client.on('connect', that.ConnectCallback);
        that.data.client.on("message", that.MessageProcess);
        that.data.client.on("error", that.ConnectError);
        that.data.client.on("reconnect", that.ClientReconnect);
        that.data.client.on("offline", that.ClientOffline);
        setTimeout(function() {
          that.setData({
            loading: true
          })
        }, 500)
      },
      onUnload: function() {
        console.log("on unload");
        var that = this;
        that.data.client.end();
      },
    
      LedControl: function(e) {
        var that = this;
        wx.vibrateShort();
        if (that.data.LEDValue[0].ButtonFlag) {
          that.setData({
            'LEDValue[0].ButtonValue': '关灯',
            'LEDValue[0].ButtonFlag': false,
            "LEDValue[0].LEDlogo": '../../images/lock-open.png',
          })
    
          that.data.client.publish(that.data.topic.LEDcontrolTopic,that.lock_open, {
            qos: 1
          });
        } else {
          that.setData({
            'LEDValue[0].ButtonValue': '开灯',
            'LEDValue[0].ButtonFlag': true,
            "LEDValue[0].LEDlogo": '../../images/lock-close.png',
          })
    
          that.data.client.publish(that.data.topic.LEDcontrolTopic,that.lock_close, {
            qos: 1
          });
        }
      },
      
    MessageProcess: function (topic, payload) {
    
      
        var that = this
        var payload_string = payload.toString();
        console.log(topic);
        
          var msg_payload = payload_string.match(/(\S*)}/)[1];
          msg_payload += "}"
          console.log(payload_string + "数据类型为：" + typeof (payload_string) + "长度：" + payload_string.length);
    
          var jsonObj = JSON.parse(msg_payload);
          //var jsonObj = JSON.stringify(payload_string)
          console.log(jsonObj.items);
          onfire.fire('topic',msg_payload,"从index传来一条消息");
      },
    
      ConnectCallback: function (connack) {
        var that = this;
        wx.showToast({
          title: '连接成功'
        })
        for (var v in that.data.topic) {
          that.data.client.subscribe(that.data.topic[v], {
            qos: 1
          });
          console.log("订阅成功...");
        }
        
      },
    
      ConnectError: function (error) {
        console.log(error)
      },
    
      ClientReconnect: function () {
        console.log("Client Reconnect")
      },
    
      ClientOffline: function () {
        console.log("Client Offline")
      },
    
});